package com.phpxiu.app.presenters;


import com.phpxiu.app.config.Constants;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.model.MsgSender;
import com.phpxiu.app.model.list.C2CConversation;
import com.phpxiu.app.model.response.C2CSenderModel;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.presenters.viewinterface.C2CManagerView;
import com.tencent.TIMConversation;
import com.tencent.TIMConversationType;
import com.tencent.TIMManager;
import com.tencent.TIMMessage;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 吴金洲 on 2016/7/25
 */
@Deprecated
public class C2CManagerPresenter {
    private static final String TAG = "C2CListWinPresenter";
    private C2CManagerView view;
    private Map<String,C2CConversation>conversationMap=new HashMap<String,C2CConversation>();//会话组
    public C2CManagerPresenter(C2CManagerView view){
        this.view = view;
    }

    /**
     * 初始化C2C会话列表
     */
    public void loadTIMConversation(){
        //获取会话个数
        long count = TIMManager.getInstance().getConversationCount();
        //遍历会话列表
        for(long i = 0; i < count; ++i) {
            //根据索引获取会话
            TIMConversation conversation = TIMManager.getInstance().getConversationByIndex(i);
            if (conversation.getType() == TIMConversationType.C2C) {
                if(!Constants.SERVER_ADMIN_ID.equals(conversation.getPeer())){//忽略管理员会话
                    conversationMap.put(conversation.getPeer(),new C2CConversation(conversation,null));
                }
            }
        }
        if(conversationMap.size()==0){
            return;
        }
        loadWithProfile();
    }

    /**
     * 检测消息是否添加新会话
     * @param message
     */
    public void addNewConversation(TIMMessage message){
        TIMConversation c=message.getConversation();
        if (c.getType()!=TIMConversationType.C2C) {
            return;
        }
        if(!conversationMap.containsKey(c.getPeer())){
            conversationMap.put(c.getPeer(),new C2CConversation(c,null));//添加新会话
            loadWithProfile(new String[]{c.getPeer()});
        }else{//更新消息
            C2CConversation c2c=conversationMap.get(c.getPeer());
            if(c2c.getSender()!=null){
                c2c.setLastMessage(message);
                if(view!=null){
                    view.refresh(conversationMap);
                }
            }
        }
    }

    /**
     * 拷贝会话资料
     */
    public void loadWithProfile(){
        String[] ids=conversationMap.keySet().toArray(new String[1]);
        if(ids.length==0){
            return;
        }
        OKHttpParam param=OKHttpParam.builder(false);
        param.put("uid", ids);
        OKHttp.post(HttpConfig.API_GET_C2C_INFO, param.jsonParam(), TAG, new OKHttpUIHandler(C2CSenderModel.class) {
            @Override
            public void onSuccess(Object model) {
                C2CSenderModel m = (C2CSenderModel) model;
                List<MsgSender> senders = m.getData();
                if (senders != null) {
                    for (MsgSender s : senders) {
                        C2CConversation c = conversationMap.get(s.getUid());
                        c.setSender(s);
                        if (conversationMap.size() == 1) {//单一会话，且消息未读
                            if (c.getUnReadNum() > 0) {
                                if (view != null) {
                                    view.gotoChat(c.getPeer(), s.getUid(), s.getNickname(), s.getAvatar());
                                }
                            }
                        }
                        //c.setLastMessage(c.getConversation().getLastMsgs(1).get(0));//同步方法，可能会耗时操作
                    }
                    if (view != null) {
                        view.refresh(conversationMap);
                    }
                }
            }

            @Override
            public void onErr(String errMsg) {
                if (view != null) {
                    view.onErr(errMsg);
                }
            }
        });
    }

    /**
     * 拷贝会话资料
     */
    public void loadWithProfile(String[] peer){
        OKHttpParam param=OKHttpParam.builder(false);
        param.put("uid", peer);
        OKHttp.post(HttpConfig.API_GET_C2C_INFO,param.jsonParam(),TAG,new OKHttpUIHandler(C2CSenderModel.class) {
            @Override
            public void onSuccess(Object model) {
                C2CSenderModel m=(C2CSenderModel)model;
                List<MsgSender>senders=m.getData();
                if(senders!=null){
                    for (MsgSender s:senders){
                        C2CConversation c=conversationMap.get(s.getUid());
                        c.setSender(s);
                        c.setLastMessage(c.getConversation().getLastMsgs(1).get(0));
                    }
                    if(view!=null){
                        view.refresh(conversationMap);
                    }
                }
            }

            @Override
            public void onErr(String errMsg) {
                if(view!=null){
                    view.onErr(errMsg);
                }
            }
        });
    }

    /***
     * 删除会话
     * @param peer 会话id
     */
    public void deleteConversation(String peer){
        if(delConversation(TIMConversationType.C2C,peer)){
            conversationMap.remove(peer);
            if(view!=null){
                view.refresh(conversationMap);
            }

        }
    }

    /**
     * 删除会话
     * @param type 会话类型
     * @param id 会话对象id
     */
    public boolean delConversation(TIMConversationType type, String id){
        return TIMManager.getInstance().deleteConversationAndLocalMsgs(type, id);
    }

    public void onDestroy(){
        view=null;
    }
}
